<script setup>
import { nextTick, onMounted, ref, watch } from 'vue';
import axios from 'axios';
import { marked } from 'marked';
import userAvatar from '../assets/icon/用户.png';
import botAvatar from '../assets/聊天头像.jpg'
import botAgent1 from '../assets/agent1.jpg'
import botAgent2 from '../assets/agent2.jpg'
import { ElMessage } from 'element-plus'
import aiChatThink from '@/components/aiChatThink.vue';

const messages = ref([])
const inputMessage = ref("")
const windowContent = ref(null)
const tags = ref([])

// 添加Bot头像相关状态
const botAvatars = ref([
  { id: 0, name: 'BossAgent', url: botAvatar },
  { id: 1, name: 'Agent1', url: botAgent1 },
  { id: 2, name: 'Agent2', url: botAgent2 }
])
const selectedBotAvatar = ref(botAvatar) // 当前选中的Bot头像
const showAvatarSelector = ref(false)   // 是否显示头像选择器

const aiChatThinkVis = ref(false)

// 渲染Markdown内容
const renderMarkdown = (content) => {
    return marked(content); // 将markdown转为HTML
}

// 解析消息内容，分离<think>标签
const parseMessageContent = (content) => {
    const parts = [];
    let remaining = content;
     // 替换Markdown二级标题符号为二级标题
    remaining = remaining.replace(/^#/gm, '#');
    while (remaining.includes("<think>") && remaining.includes("</think>")) {
        const thinkStart = remaining.indexOf("<think>");
        const thinkEnd = remaining.indexOf("</think>") + "</think>".length;

        // 添加普通内容
        if (thinkStart > 0) {
            parts.push({ text: remaining.slice(0, thinkStart), isThink: false});
        }
        // 提取<think>部分
        const thinkContent = remaining.slice(thinkStart + "<think>".length);
        parts.push({ text: thinkContent, isThink: true });

        // 剩余部分
        remaining = remaining.slice(thinkEnd);
    }
    // 添加剩余的普通内容
    if(remaining) {
        parts.push({ text: remaining, isThink: false });
    }
    return parts;
};

const loadHistory = async() => {
    try {
        const response = await axios.get("http://192.168.31.56:9000/messages")
        messages.value = response.data.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
        console.log(messages.value);
        
    }catch(error){
        console.error("获取历史记录失败",error);
    }
}
const sendMessage = () => {
    // 如果 tags 不为空，则将 tags 中的所有内容加入到 inputMessage 之前
    if (tags.value.length > 0) {
        const tagsContent = tags.value.map(tag => `|| ${tag.name} ||`).join('   ');
        inputMessage.value = `${tagsContent} -- ${inputMessage.value}`;
    }
    tags.value = []
    if(!inputMessage.value.trim()) return;
    // 先对用户消息进行存储
    const userMsg = {sender: "user",content: inputMessage.value};
    messages.value.push(userMsg);

    const userText = inputMessage.value;
    inputMessage.value = ""; // 清空输入框

    // 添加应该空的AI消息
    const botMsg = { sender: "bot",content: ""};
    messages.value.push(botMsg);

    // 使用EventSource流式接收数据
    const eventSource = new EventSource(`http://192.168.31.56:9000/stream?prompt=${encodeURIComponent(userText)}`)

    // 监听流式返回数据，拼接AI回应
    eventSource.onmessage = (event) => {
        console.log(event);
        console.log(event.data);
        
        
        // console.log(event.data);
        botMsg.content += event.data; // 拼接数据

        // 触发视图更新
        messages.value = [...messages.value]; // 结构，将列表数据拿出，重新赋值给新数组：考虑列表更新但是视图不刷新
    };
    // 监听错误，关闭连接
    eventSource.onerror = () => {
        eventSource.close();
    }
}
const clearWindow = async() => {
    try {
        const response = await axios.post("http://192.168.31.56:9000/delmessages")
        messages.value = response.data.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
    }catch(error){
        console.error("删除历史记录失败",error);
    }
}
const selectedBotAvatarFun = (url) => {
    selectedBotAvatar.value = url
    showAvatarSelector.value = false
    open2()
}
const open2 = () => {
  ElMessage({
    message: '切换成功',
    type: 'success',
  })
}
onMounted(loadHistory);
onMounted(() => {
    scrollToBottom();
})
watch(messages,() => {
    scrollToBottom();
})
const scrollToBottom = () => {
    nextTick(() => {
        if (windowContent.value) {
            windowContent.value.scrollTop = windowContent.value.scrollHeight;
        }
    })
}
const bShow = ref(true)

const selectTag = (tag) => {
    tags.value.push(tag)
    bShow.value = !bShow.value
}
const removeTag = (tag) => {
    tags.value = tags.value.filter(t => t !== tag)
}

const moreBtn = [
    {id: 0, name: 'CPU'},
    {id: 1, name: '内存'},
    {id: 2, name: '网络'},
    {id: 3, name: '磁盘'},
    {id: 4, name: '磁盘IO'},
    {id: 5, name: '内核'},
    {id: 6, name: '进程'},
    {id: 7, name: '系统指标'},
    {id: 8, name: '软中断'},
    {id: 9, name: '中断'},
    {id: 10, name: '系统'},
]
</script>

<template>
    <div class="aiChating-content">
        <div class="main-content no-padding"></div>
        <div class="aiChating-title">
            <h1 class="title-main">
                <img src="../assets/icon/机器人.png" alt="">AI运维助手
            </h1>
            <h4 class="title-content">
                使用大模型为系统运维赋能，助力优化系统性能
            </h4>
            <span>
                <button class="clear-btn" @click="clearWindow">清空历史记录</button>
            </span>
        </div>
        <div class="aiChating-window">
            <div class="window-content" ref="windowContent" :class="{ 'window-con' : !bShow , 'window-con-tags' : tags.length > 0 }">
                <div class="static-word" v-if="messages.length <= 0">
                    请输入您的问题等待解答，或添加标签有助于快速解析问题
                </div>
                <div v-for="(msg, index) in messages" :key="index" :class="['message',msg.sender]">
                    <div class="message-content-wrapper" :class="['avatar', msg.sender, msg.sender === 'bot' ? 'bot-avatar' : '']">
                        <img :src="userAvatar" alt="" v-if="msg.sender === 'user'">
                        <img :src="selectedBotAvatar" alt="" v-if="msg.sender === 'bot'" @click="showAvatarSelector = !showAvatarSelector">
                    </div>
                    <!-- 消息内容 -->
                    <div class="message-content">
                        <!-- 如果是系统消息，就解析<think>标签并且渲染MarkDown -->
                        <div v-if="msg.sender === 'bot'" class="bot-content">
                            <div
                                v-for="(part, idx) in parseMessageContent(msg.content)"
                                :key="idx"
                                :class="part.isThink && part.text.trim() ? 'think-content' : ''"
                            >
                                <div v-if="part.isThink && part.text.trim()">
                                    <!-- 渲染思考内容的Markdown -->
                                     <!-- <div v-html="renderMarkdown(part.text)"></div> -->
                                      <el-button @click="aiChatThinkVis = !aiChatThinkVis">点击</el-button>
                                </div>
                                <div v-else class="bot-content">
                                    <!-- 渲染普通内容的Markdown -->
                                     <div v-html="renderMarkdown(part.text)"></div>
                                </div>
                            </div>
                        </div>
                        <!-- 如果不是系统消息,直接显示用户输入的内容即可 -->
                         <div v-else>{{ msg.content }}</div>
                    </div>
                </div>
            </div>
            <div class="window-input" :class="{ 'window-showMore' : !bShow , 'window-tags' : tags.length > 0}">
                <div class="tags">
                    <span v-for="tag in tags" :key="tag.name">
                        {{ tag.name }}
                        <button @click="removeTag(tag)">x</button>
                    </span>
                </div>
                <div class="window-batis" v-if="bShow">
                    <button class="input-voice input-btn">
                        <img src="../assets/icon/语音输入.png" alt="">
                    </button>
                    <button class="imput-morebtn input-btn" @click="bShow = !bShow">
                        <img src="../assets/icon/更多.png" alt="">
                    </button>
                    <input v-model="inputMessage" @keyup.enter="sendMessage" type="text" name="aiChatingUser" id="aiChatingUser" placeholder="输入内容...">
                    <button type="submit" name="submit" class="submit-button" @click="sendMessage">
                        <img src="../assets/icon/发送.png" alt="">
                    </button>
                </div>
                <div class="window-more" v-else>
                    <button class="input-btn btn-more" @click="bShow = !bShow">
                        <img src="../assets/icon/返回chating.png" alt="">
                    </button>
                    <div class="key-items">
                        <div class="key-item" v-for="item in moreBtn" :key="item.id" @click="selectTag(item)">
                            {{ item.name }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <el-dialog
            v-model="showAvatarSelector"
            title=""
            width="500"
            align-center
        >
            <div class="avatar-options">
                <div
                    v-for="avatar in botAvatars"
                    :key="avatar.id"
                    class="bot-avatar-sel"
                    @click="selectedBotAvatarFun(avatar.url)"
                >
                <el-tooltip
                    effect="dark"
                    :content="avatar.name"
                    placement="top-start"
                >
                    <img :src="avatar.url" alt="">
                </el-tooltip>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showAvatarSelector = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog
            v-model="aiChatThinkVis"
            title="思考过程"
            width="800"
            align-center
        >
            <ai-chat-think></ai-chat-think>
            <template #footer>
                <el-button @click="aiChatThinkVis = !aiChatThinkVis">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.aiChating-content {
    padding: 20px 35px 20px;
    background: linear-gradient(#0048FF,#5CC6FF);
    width: 100%;
    height: 100%;
    border-top-left-radius: 35px;
    border-bottom-left-radius: 35px;
    position: relative;
}
.aiChating-content .aiChating-title {
    width: 630px;
    height: 80px;
    margin: 0 auto;
    text-align: center;
    margin-bottom: 20px;
}
.clear-btn {
    position: absolute;
    top: 20px;
    right: 40px;
    border: 0;
    padding: 8px 10px;
    font-size: 14px;
    background-color: #fff;
    color: rgb(0,81,255);
    font-weight: 700;
    border-radius: 20px;
}
.clear-btn:hover {
    cursor: pointer;
}
.aiChating-title .title-main {
    font-size: 40px;
    color: #fff;
    font-weight: 800;
    display: inline-block;
    margin-bottom: 0;
    text-align: center;
}
.title-main img {
    margin-right: 8px;
    margin-bottom: 5px;
}
.aiChating-title .title-content {
    font-size: 20px;
    color: #fff;
    font-weight: 700;
    display: inline-block;
    margin-bottom: 0;
}
.aiChating-window {
    width: 100%;
    height: calc(100% - 120px);
    border-radius: 20px;
    background-color: #FBFBFB;
}
.aiChating-window .window-content {
    width: 100%;
    height: 85%;
    padding: 20px;
    overflow-y: auto;
    scroll-behavior: smooth;
}

/* 消息盒子整体样式 */
.message {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;
}

/* 用户消息样式 */
.message.user {
    justify-content: flex-end; /* 用户消息靠右对齐 */
}

/* 用户消息框在头像左边 */
.message.user .message-content-wrapper {
    order: 2; /* 将头像放在右边 */
    margin-left: 10px; /* 消息框与头像的间距 */
    margin-right: 0;
}

.message.user .message-content {
    order: 1; /* 消息框放在头像左边 */
}

/* 机器人消息样式 */
.message.bot {
    justify-content: flex-start; /* 机器人消息靠左对齐 */
}

/* 消息头像样式 */
.message-content-wrapper {
    display: flex;
    align-items: center;
    margin-right: 10px; /* 机器人头像右侧间距 */
}
.message-content-wrapper img {
    width: 40px;
    height: 40px;
}
.message.user .message-content-wrapper {
    margin-left: 10px; /* 用户头像左侧间距 */
    margin-right: 0;
}

/* 头像图片样式 */
.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
    background-color: #c6c6c6; /* 默认背景色 */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: center;
    align-items: center;
}
.avatar img {
    width: 30px;
    height: 30px;
    /* object-fit: cover; */
}
.bot-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
}
.bot-avatar img{
    width: 40px;
    height: 40px;
}
.bot-avatar-sel {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    overflow: hidden;
}
.bot-avatar-sel:hover {
    cursor: pointer;
}
.bot-avatar-sel img{
    width: 60px;
    height: 60px;
}
.avatar-options {
    display: flex;
    justify-content: space-around;
}
.avatar-options span {
    font-size: 14px;
    color: #333;
}
/* 消息内容样式 */
.message-content {
    max-width: 70%;
    padding: 10px 25px;
    border-radius: 10px;
    font-size: 14px;
    line-height: 1.5;
    word-wrap: break-word;
    overflow-wrap: break-word;
    background-color: #f2f3f5; /* 默认背景色 */
    color: #333;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* 用户消息内容样式 */
.message.user .message-content {
    background-color: #0048FF; /* 用户消息背景色 */
    color: #fff; /* 用户消息字体颜色 */
    text-align: right; /* 用户消息右对齐 */
}

/* 机器人消息内容样式 */
.message.bot .message-content {
    background-color: #f2f3f5; /* 机器人消息背景色 */
    color: #333; /* 机器人消息字体颜色 */
    text-align: left; /* 机器人消息左对齐 */
}

/* Markdown 渲染内容样式 */
.message-content .think-content {
    font-size: 12px; /* 思考部分字体更小 */
    color: #7e7e7e; /* 浅色字体 */
    background-color: #eaf5ffe2; /* 思考内容背景色 */
    padding: 5px;
    border-radius: 5px;
    display: inline-block;
    margin-top: 5px;
    margin-bottom: 5px;
}
.think-content div {
    display: inline !important;
}
.message-content .bot-content {
    width: 100%;
}
.aiChating-window .window-input {
    width: 100%;
    height: 15%;
    border-bottom-left-radius: 20px;
    border-bottom-right-radius: 20px;
    box-shadow: 10px 0 10px rgba(0,0,0,0.1);
    background-color: #fff;
    padding: 10px;
    transition: all 0.3s ease;
    position: relative;
}
.window-input .window-batis {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.window-input .window-more {
    width: 100%;
    height: 100%;
    overflow: auto;
}
.window-input .tags {
    position: absolute;
    left: 100px;
    top: 5px;
}
.tags span {
    display: inline-block;
    background-color: #003Cff;
    padding: 5px 14px;
    margin-right: 8px;
    border-radius: 10px;
    color: #fff;
    font-size: 12px;
}
.tags button {
    margin-left: 5px;
    cursor: pointer;
    border: 0;
    background-color: #003Cff;
    color: #fff;
}
.window-more .key-items {
    width: 100%;
    height: 80%;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    justify-content: space-between;
    gap: 5%;
    padding: 0 5%;
}
.key-items .key-item {
    flex: 1 1 auto;
    min-width: 14%;
    max-width: 16%;
    padding: 8px 10px;
    font-size: 16px;
    border-radius: 10px;
    color: #fff;
    background-color: rgb(157, 206, 255);
    align-items: center;
    margin-bottom: 10px;
    text-align: center;
    cursor: pointer;
}
.input-btn {
    width: 30px;
    height: 30px;
    align-items: center;
    border: 0;
    background-color: #fff;
    border-radius: 50%;
    cursor: pointer;
}
.input-btn img {
    width: 25px;
    height: 25px;
}
.imput-morebtn {
    margin-left: 8px;
}
.input-btn.btn-more {
    width: 40px;
    height: 40px;
}
.input-btn.btn-more img {
    width: 35px;
    height: 35px;
}
.window-batis input[type="text"] {
    flex: 1;
    height: 40px;
    border: none;
    border-radius: 20px;
    padding: 0 16px;
    margin: 0 12px;
    font-size: 16px;
    background-color: #F2F3F5;
    outline: none;
}

.window-batis .submit-button {
    width: 50px;
    height: 40px;
    border: none;
    background-color: #0048FF;
    border-radius: 20px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.window-batis .submit-button img {
    width: 22px;
    height: 22px;
}

.window-input.window-showMore {
    height: 30%;
    transition: all 0.3s ease;
}
.window-content.window-con {
    height: 70%;
    transition: all 0.3s ease;
}

.window-input.window-tags .window-batis {
    margin-top: 14px;
}
.window-content .static-word {
    padding: 10px 15px;
    border-radius: 15px;
    background-color: #bcbcbc;
    color: #fff;
    font-size: 14px;
    text-align: center;
    margin: 0 auto;
}
/* From Uiverse.io by adamgiebl */ 
.dots-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.dot {
  height: 20px;
  width: 20px;
  margin-right: 10px;
  border-radius: 10px;
  background-color: #b3d4fc;
  animation: pulse 1.5s infinite ease-in-out;
}

.dot:last-child {
  margin-right: 0;
}

.dot:nth-child(1) {
  animation-delay: -0.3s;
}

.dot:nth-child(2) {
  animation-delay: -0.1s;
}

.dot:nth-child(3) {
  animation-delay: 0.1s;
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    background-color: #b3d4fc;
    box-shadow: 0 0 0 0 rgba(178, 212, 252, 0.7);
  }

  50% {
    transform: scale(1.2);
    background-color: #6793fb;
    box-shadow: 0 0 0 10px rgba(178, 212, 252, 0);
  }

  100% {
    transform: scale(0.8);
    background-color: #b3d4fc;
    box-shadow: 0 0 0 0 rgba(178, 212, 252, 0.7);
  }
}

.message-content h1,
.message-content h2,
.message-content h3,
.message-content h4,
.message-content h5,
.message-content h6 {
  font-weight: bold;
  margin: 8px 0 4px 0;
  /* 给不同级别标题不同字体大小 */
}
.message-content h1 { font-size: 2em; }
.message-content h2 { font-size: 1.7em; }
.message-content h3 { font-size: 1.4em; }
.message-content h4 { font-size: 1.2em; }
.message-content h5 { font-size: 1.1em; }
.message-content h6 { font-size: 1em; }
.think-content h1, .think-content h2, .think-content h3,
.think-content h4, .think-content h5, .think-content h6 {
  font-weight: bold;
  margin: 8px 0 4px 0;
}

.think-content h3 { font-size: 1.1em; }


</style>